<?php
/**
 * 登录 session 检测
 * User: Joshua Conero
 * Date: 2019/8/21
 * Time: 22:53
 * Email: conero@163.com
 */

// config 数据结构:
//      config = [use: bool/开启, times:int/数次, session_key: string/session键值, lock_minute:int/锁定分钟];
// session 数据结构：
//      session[config.session_key] = [times: 0/数次, lock:bool/锁定标记, lock_mtime:int/锁定时间];

namespace app\common\service;


use hyang\DateDiff;
use think\facade\Config;

class LoginSessionChecker
{
    protected static $config = false;
    protected static $isUse = false;
    private static $_lockMaxTimes = 30; // 最长锁定时间
    private static $_currLockTimes = 30;// 当前锁定时间

    /**
     * 获取配置参数
     * @return bool|mixed
     */
    static function getConf(){
        if(!self::$config){
            self::$config = Config::get('app.login_check', true);
            if(is_array(self::$config) && (self::$config['use'] ?? false)){
                self::$_lockMaxTimes = self::$config['lock_minute'];
                self::$isUse = true;
            }
        }
        self::$_currLockTimes = self::$_lockMaxTimes;
        return self::$config;
    }

    /**
     * 入口统计
     */
    static function record(){
        $conf = self::getConf();
        if(self::$isUse){
            $session_key = $conf['session_key'];
            $data = session($session_key);
            $data = is_array($data)? $data: [];
            $data['times'] = ($data['times'] ?? 0) + 1;
            session($session_key, $data);
        }
    }

    /**
     * 锁定判断
     * @return bool
     */
    static function isLock(){
        $isLock = false;
        $conf = self::getConf();
        if(self::$isUse){
            $session_key = $conf['session_key'];
            $data = session($session_key);
            $data = is_array($data)? $data: [];
            $times = ($data['times'] ?? 0);
            if(!($data['lock'] ?? false)){
                if($times >= $conf['times']){
                    $data['lock'] = true;
                    $data['lock_mtime'] = time();
                    session($session_key, $data);
                    $isLock = true;
                }
            }else{
                $isLock = true;
                // 超时自动解除
                $lock_mtime = $data['lock_mtime'];
                $diff = new DateDiff(intval($lock_mtime));
                $minute = $diff->minute;
                self::$_currLockTimes = self::$_lockMaxTimes - $minute;
                if($minute >= $conf['lock_minute']){
                    $data = [
                        'times' => 0
                    ];
                    session($session_key, $data);
                    $isLock = false;
                }
            }
        }
        return $isLock;
    }

    /**
     * 获取被锁定的时间
     * @return int
     */
    static function getLockMinute(){
        return (self::$_currLockTimes ?? self::$_lockMaxTimes);
    }
}